package com.zynote.nfhoujie.web.controller;

import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.gson.Gson;
import com.zynote.commons.utils.EncryptUtil;
import com.zynote.nfhoujie.commons.constants.CommodityConstants;
import com.zynote.nfhoujie.commons.utils.SessionUtil;
import com.zynote.nfhoujie.model.User;
import com.zynote.nfhoujie.model.UserInfo;
import com.zynote.nfhoujie.service.IUserService;
import com.zynote.nfhoujie.web.form.UserForm;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 
 * @className:LoginRegisterController.java
 * @classDescription:前台页面管理
 * @author: AIDAN SU
 * @createTime: 2012-10-25
 *
 */

@Controller
@RequestMapping
public class LoginRegisterController {
	
	@Resource
	private IUserService userService;
	
	/**
	 * 跳转到欢迎页面（WAP）
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/wap/index" ,method = {RequestMethod.GET})
	public String welcome(){
		return "/wap/index";
	}
	
	/**
	 * 跳转到菜单页面（WAP）
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/wap/menu" ,method = {RequestMethod.GET})
	public String menu(){
		return "/wap/menu";
	}
	
	/**
	 * 登出
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/logout" ,method = {RequestMethod.GET})
	public String logout(HttpServletRequest request){
		SessionUtil.logout(request);
		return "redirect:login";
	}
	
	/**
	 * 跳转到用户登录页面
	 * @return
	 */
	@RequestMapping(value="/login" ,method = {RequestMethod.GET})
	public String login(ModelMap modelMap , HttpServletRequest request){
		
		// 判断用户是否已经登陆
		if( SessionUtil.isLogin( request ) ){
			modelMap.put("user", SessionUtil.getUserFromSession(request));
			return "/commodity/index";
		}else{
			return "/login";
		}
	}
	
	/**
	 * 跳转到用户登录页面（WAP）
	 * @return
	 */
	@RequestMapping(value="/wap/login" ,method = {RequestMethod.GET})
	public String loginWap(ModelMap modelMap , HttpServletRequest request){
		
		// 判断用户是否已经登陆
		if( SessionUtil.isLogin( request ) ){
			modelMap.put("user", SessionUtil.getUserFromSession(request));
			return "/wap/startover";
		}else{
			return "/wap/login";
		}
	}
	
	/**
	 * 跳转到用户注册页面（WAP）
	 * @return
	 */
	@RequestMapping(value="/wap/register" ,method = {RequestMethod.GET})
	public String registerWap(ModelMap modelMap , HttpServletRequest request){
		
		// 判断用户是否已经登陆
		if( SessionUtil.isLogin( request ) ){
			modelMap.put("user", SessionUtil.getUserFromSession(request));
			return "/wap/commodity";
		}else{
			return "/wap/register";
		}
	}
	
	/**
	 * 用户登录
	 * @param modelMap
	 * @param request
	 * @return
	 */
	@RequestMapping( value="/logining", method =RequestMethod.POST)
	@ResponseBody
	public String logining(@ModelAttribute UserForm userForm ,  HttpServletRequest request ){
		
		// 响应结果
		Map<String,String> response = null ;
		// 校验用户提交信息
		response = validLogin(userForm, request) ;
		
		if( response == null ){
			// 查数据库
			User user = userService.findUserByUsername( userForm.getUsername() );
			String shaPwd = null ;
			try {
				shaPwd = EncryptUtil.encryptSHA( userForm.getPassword() ) ;
			} catch (NoSuchAlgorithmException e) {
				shaPwd = "" ;
			}
			
			if( user != null && shaPwd.equals( user.getPassword() ) ){
				SessionUtil.login(user, request);
				response = getResponse("200", "success", "登录成功");
			}else{
				response = getResponse("-1", "fail", "用户名或密码不正确");
			}
			
		}
		Gson gson = new Gson();
		return gson.toJson( response ) ;
	}
	
	/**
	 * 注册账号
	 * @param userForm
	 * @param modelMap
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/registering" ,method = RequestMethod.POST)
	@ResponseBody
	public String registering( @ModelAttribute UserForm userForm ,  HttpServletRequest request ){
		
		// 响应结果
		Map<String,String> response = null ;
		
		// 校验用户提交信息
		response = validRegister(userForm, request) ;
		if( response == null ){
			User existUser = userService.findUserByUsername( userForm.getUsername() );
			
			// 判断用户名是否已注册
			if( existUser == null  ){
				
				// 验证通过，保存用户信息
				User user = new User();
				
				// 拷贝对象
				try {
					PropertyUtils.copyProperties(user, userForm);
				} catch (Exception e) {
					e.printStackTrace();
				} 
				
				// 密码加密
				try {
					user.setPassword( EncryptUtil.encryptSHA( user.getPassword() )  );
				} catch (NoSuchAlgorithmException e) {
					e.printStackTrace();
				}
				
				// 判断用户类型
				user.setUserType( userForm.getUserType() == 1 ? CommodityConstants.USER_TYPE_PERSONAL : CommodityConstants.USER_TYPE_COMPANY);
				
				// 设置用户状态
				user.setUserStatus( CommodityConstants.USER_STATUS_NORMAL );
				
				// 用户创建时间
				Date date = new Date();
				user.setCreateTime( date ) ;
				user.setLastUpdateTime( date );
				
				Long uid = userService.createUserAndUserInfo(user, new UserInfo());
				
				response = getResponse("200", "success", "用户注册成功");
				response.put("uid", ""+uid);
				
				if( uid != null && uid > 0 ){
					//注册成功后，创建用户session，实现用户自动登录
					SessionUtil.login(user, request);
				}
				
			}else{
				response = getResponse("-1", "fail", "注册失败，该用户名已存在");
			}
			
		}
			
		Gson gson = new Gson();
		return gson.toJson( response ) ;
	}
	
	/**
	 * 注册账号
	 * @param userForm
	 * @param modelMap
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/wap/registering" ,method = RequestMethod.POST)
	@ResponseBody
	public String registeringWap( @ModelAttribute UserForm userForm ,  HttpServletRequest request ){
		
		// 响应结果
		Map<String,String> response = null ;
		
		// 校验用户提交信息
		response = validRegister(userForm, request) ;
		if( response == null ){
			User existUser = userService.findUserByUsername( userForm.getUsername() );
			
			// 判断用户名是否已注册
			if( existUser == null  ){
				
				// 验证通过，保存用户信息
				User user = new User();
				
				// 拷贝对象
				try {
					PropertyUtils.copyProperties(user, userForm);
				} catch (Exception e) {
					e.printStackTrace();
				} 
				
				// 密码加密
				try {
					user.setPassword( EncryptUtil.encryptSHA( user.getPassword() )  );
				} catch (NoSuchAlgorithmException e) {
					e.printStackTrace();
				}
				
				// 判断用户类型
				user.setUserType( userForm.getUserType() == 1 ? CommodityConstants.USER_TYPE_PERSONAL : CommodityConstants.USER_TYPE_COMPANY);
				
				// 设置用户状态
				user.setUserStatus( CommodityConstants.USER_STATUS_NORMAL );
				
				// 用户创建时间
				Date date = new Date();
				user.setCreateTime( date ) ;
				user.setLastUpdateTime( date );
				
				Long uid = userService.createUserAndUserInfo(user, new UserInfo());
				
				response = getResponse("200", "success", "用户注册成功");
				response.put("uid", ""+uid);
				
				if( uid != null && uid > 0 ){
					//注册成功后，创建用户session，实现用户自动登录
					SessionUtil.login(user, request);
				}
				
			}else{
				response = getResponse("-1", "fail", "注册失败，该用户名已存在");
			}
			
		}
			
		Gson gson = new Gson();
		return gson.toJson( response ) ;
	}
	
	/**
	 * 获取响应Map对象
	 * @param responseCode
	 * @param responseMsg
	 * @param info
	 * @return
	 */
	private Map<String,String> getResponse(String responseCode ,String responseMsg ,String info){
		Map<String,String> response = new HashMap<String,String>();
		response.put("responseCode", responseCode) ;
		response.put("responseMsg", responseMsg) ;
		response.put("info", info) ;
		return response ;
	}
	
	/**
	 * 校验用户登录信息
	 * @param userForm
	 * @param request
	 * @return
	 */
	private Map<String ,String> validLogin(UserForm userForm ,HttpServletRequest request ){
			
      //验证用户名，必须由字母，数字，下划线组成，长度3到30  
	  Pattern usernamePattern = Pattern.compile( "^[a-zA-Z0-9_-]{3,30}$" );  
	  Matcher usernameMatcher = usernamePattern.matcher( userForm.getUsername() );  
	  if( !usernameMatcher.matches() ){
		  return getResponse("-1","fail","用户名不正确");
	  }
	  
      //验证密码，必须由字母，数字，下划线组成，长度6到30  
	  Pattern passwordPattern = Pattern.compile( "^[a-zA-Z0-9_-]{6,30}$" );  
	  Matcher passwordMatcher = passwordPattern.matcher( userForm.getPassword() );  
	  if( !passwordMatcher.matches() ){
		  return getResponse("-1","fail","密码不正确");
	  }
		  
		return null ;
	}
	
	/**
	 * 校验注册账号信息
	 * @param userForm
	 * @param request
	 * @return 如果返回null，则验证通过
	 */
	private Map<String,String> validRegister( UserForm userForm, HttpServletRequest request ){

		  //验证用户名，必须由字母，数字，下划线组成，长度3到30  
		  Pattern usernamePattern = Pattern.compile( "^[a-zA-Z0-9_-]{3,30}$" );  
		  Matcher usernameMatcher = usernamePattern.matcher( userForm.getUsername() );  
		  if( !usernameMatcher.matches() ){
			  return getResponse("-1","fail","用户名不正确");
		  }
		  
		  //验证密码，必须由字母，数字，下划线组成，长度6到30  
		  Pattern passwordPattern = Pattern.compile( "^[a-zA-Z0-9_-]{6,30}$" );  
		  Matcher passwordMatcher = passwordPattern.matcher( userForm.getPassword() );  
		  if( !passwordMatcher.matches() ){
			  return getResponse("-1","fail","密码不正确");
		  }
		  
		  //用户密码与确认密码是否一致
		  if( !userForm.getPassword().equals( userForm.getRepassword() ) ){
			  return getResponse("-1","fail","密码与确认密码不一致");
		  }
		  
          //验证手机号码，必须由字母，数字，下划线组成，长度3到30  
		  Pattern phonePattern = Pattern.compile( "^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$" );  
		  Matcher phoneMatcher = phonePattern.matcher( userForm.getTelPhone() );  
		  if( !phoneMatcher.matches() ){
			  return getResponse("-1","fail","手机号码不正确");
		  }	  
			
          //验证邮箱地址
		  Pattern emailPattern = Pattern.compile( "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$" );  
		  Matcher emailMatcher = emailPattern.matcher( userForm.getEmail() );  
		  if( !emailMatcher.matches() ){
			  return getResponse("-1","fail","邮箱地址不正确");
		  }
		  
		return null ;
	}
	
}
